package com.blue.waffle.iwc.utils;

import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.assets.AssetManager;
import com.badlogic.gdx.audio.Sound;
import com.blue.waffle.iwc.utils.LruCache.OldEntryRemovedListener;

/**
 * A simple manager that manages the sound effects. Inspired by Gustavo Steigert
 * 
 * "https://code.google.com/p/steigert-libgdx/source/browse/tags/post-20120314/tyrian-game/src/com/blogspot/steigert/tyrian/services/SoundManager.java"
 * 
 * @author Wenbin
 * 
 */
public class SoundManager implements SoundsManager,
		OldEntryRemovedListener<SoundManager.IWCSound, Sound> {

	public static final String TAG = "com.blue.waffle.iwc.utils.SoundManager";

	private LruCache<SoundManager.IWCSound, Sound> cache;
	private boolean active = true;
	private float volume = 0.7f;
	private final AssetManager assetManager;
	
	public enum IWCSound {

		TICK("sounds/tick.mp3"), ACCEPT("sounds/accept.mp3");

		private final String fileName;

		private IWCSound(String name) {
			this.fileName = name;
		}

		public String getFileName() {
			return fileName;
		}
	}

	public SoundManager(AssetManager assetManager) {
		cache = new LruCache<SoundManager.IWCSound, Sound>(10);
		cache.setOldEntryRemovedListener(this);
		this.assetManager=assetManager;
	}

	public void play(IWCSound sound) {
		if (!active) {
			return;
		}
		Sound soundInstance = cache.get(sound);
		if (soundInstance == null) {
			soundInstance =assetManager.get(sound.getFileName(), Sound.class);
			cache.put(sound, soundInstance);
		}
		soundInstance.play(volume);
	}

	public void setVolume(float volume) {
		if (volume < 0 || volume > 1) {
			throw new IllegalArgumentException(
					"Volume can only set from 0 - 1.");
		}
		this.volume = volume;
	}

	public float getVolume() {
		return volume;
	}

	public boolean isActive() {
		return active;
	}

	public void setActive(boolean active) {
		this.active = active;
	}

	@Override
	public void dispose() {
		Gdx.app.log(TAG, "disposing all sound effects");
		for (Sound sound : cache.values()) {
			sound.dispose();
		}
	}

	@Override
	public void notifyOldEntryRemoved(IWCSound key, Sound value) {
		value.dispose();
	}

	@Override
	public void loadAssets() {
		for (IWCSound sound : IWCSound.values()) {
			assetManager.load(sound.getFileName(),Sound.class);
		}
	}

}
